package cn.chitanda.weather.ui.AddCity

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.viewModelScope
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import cn.chitanda.weather.R
import cn.chitanda.weather.data.weather.Basic
import cn.chitanda.weather.ui.PlaceViewModel
import kotlinx.android.synthetic.main.resultlist_itme.view.*
import kotlinx.coroutines.launch

class ResultAdapter(private val viewModel: PlaceViewModel) :
    ListAdapter<Basic, ResultViewHolder>(DiffCallBack) {
    object DiffCallBack : DiffUtil.ItemCallback<Basic>() {
        override fun areItemsTheSame(oldItem: Basic, newItem: Basic): Boolean {
            return oldItem.cid == newItem.cid
        }

        override fun areContentsTheSame(oldItem: Basic, newItem: Basic): Boolean {
            return oldItem == newItem
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultViewHolder {
        return ResultViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.resultlist_itme,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ResultViewHolder, position: Int) {
        val basic = getItem(position)
        holder.itemView.result_location.text = basic.location
        holder.itemView.result_parent.text = basic.parent_city
        holder.itemView.result_admin.text = basic.admin_area
        holder.itemView.setOnClickListener {
            viewModel.viewModelScope.launch {
                viewModel.insertCity(basic)
            }
            holder.itemView.findNavController()
                .navigateUp()
        }
    }

}

class ResultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)